<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>订单预览</title>
    <link rel="stylesheet" href="./style.css"/>

</head>
<body>
<div id="app">
    <div class="my-div" id="myDiv" ref="myDivRef" style="display: none;z-index: 1">
        <div class="user-print"
             :style="{width:(userPrint.paperWide*multiple)+'px',height:'auto'}">
            <!--(userPrint.paperHigh*multiple)+'px'-->

            <!-- 抬头 -->
            <div v-if="operationPms.titleName" class="user-print-1" data-type="text"
                 :data-text="operationPms.titleName+'订货单据'"
                 :style="{fontSize:userPrint.titleFont+'px'}"
                 style="text-align: center;margin: 8px 0;font-weight: bold;border-color: black;display: flex;justify-content: center;align-items: center;">
                <!--                <img v-if="operationPms.titleImgUrl" :src="operationPms.titleImgUrl"  style="height: 30px;margin-right: 5px;">-->
                {{operationPms.titleName||''}}{{type===1?'订货单据':'销售订单'}}
            </div>

            <!-- 搜索框 -->
            <div style="display:flex;flex-wrap: wrap;">
                <template v-for="item of userPrint.billFields">
                    <div v-if="getColumnType(item,1)" style="display:flex;margin: 0 10px 10px 0;">
                        <div class="user-print-description" style="font-weight: bold;" data-type="text"
                             :data-text="item.description+':'">{{item.description}}:
                        </div>
                        <div class="user-print-value" style="margin-left:5px;margin-right:10px;min-width: 6rem;"
                             data-type="text"
                             :data-text="operationPms[item.aName]">{{operationPms[item.aName]}}
                        </div>
                    </div>
                </template>
            </div>

            <!-- 表格 -->
            <table>
                <thead>
                <tr class="p-tr">
                    <template v-for="item of userPrint.billDetailFieldsOne">
                        <th class="p-th" :style="{width:((item.width)||'100')+'px',size:((item.size)||'12')+'px'}"
                            data-type="text"
                            :data-text="item.description">
                            {{item.description}}
                        </th>
                    </template>
                </tr>
                </thead>
                <tbody>
                <tr class="p-tr" v-for="item in list" :key="item.id">
                    <template v-for="item2 of userPrint.billDetailFieldsOne">
                        <td class="p-td" :class="!item2.isBreak?'dont-break':''"
                            :style="{width:((item2.width)||'0')+'px',size:((item2.size)||'12')+'px'}">
                            {{ item[item2.aName] }}
                        </td>
                    </template>
                </tr>

                </tbody>
            </table>

            <!-- 合计 -->
            <table>
                <tbody>
                <tr class="p-tr" v-for="item in totalList" :key="item.index">
                    <template v-for="item2 of totalMap">
                        <td class="p-td"
                            :style="{width:((item2.width)||'100')+'px',size:((item2.size)||'12')+'px'}">
                            {{item[item2.aName]}}
                        </td>
                    </template>
                </tr>

                </tbody>
            </table>

            <!-- 底部搜索 -->
            <div style="display:flex;flex-wrap: wrap;margin-top: 10px;">
                <template v-for="item of userPrint.billFields">
                    <div v-if="getColumnType(item,2)" style="display:flex;margin: 0 10px 10px 0;"
                         :style="{width:item.width100?'100%':'auto'}">
                        <div class="user-print-description" style="font-weight: bold;" data-type="text"
                             :data-text="item.description+':'">{{item.description}}:
                        </div>
                        <div class="user-print-value" style="margin-left:5px;min-width: 4rem;" data-type="text"
                             :data-text="operationPms[item.aName]">{{operationPms[item.aName]}}
                        </div>
                    </div>
                </template>
            </div>

            <!--底部展示-->
            <div v-if="bottomData" v-html="bottomData"></div>
        </div>
    </div>
    <div id="canvasDiv" style="overflow: auto;"></div>
    <div class="loading-container" id="loadingContainer">
        <div class="loading-spinner"></div>
    </div>

</div>
<!--<canvas id="myCanvas"></canvas>-->
<!--<button id="downloadBtn" onclick="downloadImage()">Download Image</button>-->

<!--<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>-->
<!--<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>-->
<script src="../utils/vue.js"></script>
<!--<script src="https://unpkg.com/http-vue-loader"></script>-->
<script src="../utils/http-vue-loader.js"></script>
<!--<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>-->
<script src="../utils/jquery-3.4.1.min.js"></script>
<!--<script type="text/javascript" src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>-->
<script src="../utils/html2canvas.js"></script>
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script type="text/javascript" src="https://unpkg.com/@dcloudio/uni-webview-js@0.0.3/index.js"></script>
<script src="../utils/common.js"></script>


<script type="text/javascript">
    Vue.use(httpVueLoader);
    new Vue({
        el: '#app',
        data: {
            id: '',
            authorization: '',
            dataObj: {},
            baseUrl: 'https://xxx:8443',
            operationPms: {},
            list: [],
            userPrint: {},
            res1: {},
            res2: {},
            multiple: 7,
            totalMap: [],
            totalList: [],
            type: 1,
            bottomData: ''
        },
        created() {
            this.id = this.getQueryString('id');
            this.authorization = this.getQueryString('authorization');
            if (this.getQueryString('type')) {
                this.type = parseInt(this.getQueryString('type')) || 1
            }
            console.log('id:', this.id);
            console.log('authorization:', this.authorization);
            this.getData();
        },
        methods: {
            /*查询底部抬头展示*/
            getBillTitleBelow(id) {
                return new Promise((resolve, reject) => {


                    return  resolve()
                    ajax('Get', '/App/GetBillTitleBelow?id=' + id, {}, (res) => {
                        let data = res.data;

                        if (this.type === 1) {//订单
                            this.bottomData = data.orderBottom || '';
                        } else if (this.type === 2) {//销售
                            this.bottomData = data.saleBottom || '';

                        }


                        resolve(data)
                    }, (e) => {
                        reject()
                    }, this.authorization);
                })
            },
            /*查询打印配置*/
            getBillColumnSetting() {

                let mid = '4dec3753-d77d-4b34-9f44-9419543def59';
                if (this.type === 2) {//销售
                    mid = 'c03c5ef6-65ec-41fd-a766-c3ad8c589d04';
                }

                ajax('Get', '/App/Role/GetBillColumnSetting/' + mid, {}, (res) => {
                    let data = res.data;
                    this.res2 = res;
                    if (data) {
                        data.userPrint.billDetailFieldsOne = JSON.parse(data.userPrint.billDetailFieldsOne).filter(row => row.checked && row.width > 0);
                        data.userPrint.billFields = JSON.parse(data.userPrint.billFields).filter(row => row.checked);
                        this.userPrint = data.userPrint;
                        //上面和下面展示处理
                        let productRemark = false;//产品备注
                        for (let item of this.userPrint.billFields) {
                            if (item.aName === 'productRemark') {
                                productRemark = item.checked;
                            }
                            console.log(item.description, '----', item.aName, item.checked)
                        }
                        //列处理
                        for (let item of this.userPrint.billDetailFieldsOne) {
                            for (let item2 of this.list) {
                                if (typeof item2[item.aName] === 'boolean') {
                                    if (item2[item.aName]) {
                                        item2[item.aName] = "是"
                                    } else {
                                        item2[item.aName] = "否"
                                    }
                                }
                                if (!productRemark) {
                                    if (item.aName === 'auditRemark' || item.aName === 'remark') {
                                        if (item2[item.aName]) {
                                            item2[item.aName] = item2[item.aName].split('【产品】')[0];
                                        }
                                    }
                                }
                            }
                        }
                        //合计方法
                        this.totalListLoad(this.userPrint.billDetailFieldsOne, this.list).then(() => {
                            console.log(this.userPrint);
                            document.getElementById("myDiv").style.display = '';
                            this.$nextTick(() => {
                                // document.getElementById("loadingContainer").style.display = 'none';
                                this.html2canvasFun()
                            })
                        });
                    }
                }, (e) => {
                    alert('请求异常！');

                }, this.authorization);
            },
            getData() {
                let method = 'Get';
                let api = '/App/Order/GetUserOrderInfo?id=' + this.id;
                let pms = {};
                if (this.type === 2) {//销售
                    api = '/App/SaleManage/Edit?voucheCode=' + this.id;
                }
                ajax(method, api, pms, (res) => {
                    this.res1 = res;
                    let data = res.data;
                    if (data) {
                        if (!data.statusName)
                            data.statusName = data.status === 1 ? '已审核' : '待审核';

                        if (data.settleWay === 0) {
                            data.settleWayName = '先付';
                        } else if (data.settleWay === 1) {
                            data.settleWayName = '现金';
                        } else if (data.settleWay === 2) {
                            data.settleWayName = '挂账';
                        }

                        // data.area=data.provinceName+data.cityName;
                        data.area = data.cityName;
                        data.voucheDate = data.voucheDate.split(' ')[0];
                        let childrens = [];
                        for (let item of data.details) {
                            delete item.parentId;
                            if (item.childrens && Array.isArray(item.childrens)) {
                                item.familyId = item.id;
                                for (let item2 of item.childrens) {
                                    item2.name = item2.goodsName;
                                    // item2.code = item2.goodsCode;
                                    // item2.isChildren = true;
                                    item2.parentId = item.familyId;
                                    childrens.push({
                                        ...item2
                                    });
                                }
                            }
                        }
                        data.details = data.details.concat(childrens);
                        this.operationPms = data;
                        this.list = data.details;
                        for (let item of this.operationPms.files) {
                            item.url = item.path;
                        }
                        this.files = [...this.operationPms.files];
                        let index = 1;
                        for (let item of this.list) {
                            item.index = index;
                            index += 1;
                            item.porductImagesList_ = item.porductImagesList.filter(row => row.groupId === item.colourName || row.groupId ===
                                '');
                            if (item.porductImagesList_ && item.porductImagesList_.length > 0) {
                                item.imgUrl = item.porductImagesList_[0].path;
                            }
                            if (!item.imgUrl) {
                                item.imgUrl = this.imgUrl;
                            }
                            if (item.deliveryDate) {
                                item.deliveryDate = item.deliveryDate.split(' ')[0];
                            }

                            // if (item.status > 3) {
                            // 	this.getQualityImg(item.batchNo);
                            // }
                        }
                        //有关联产品排序
                        if (this.list.filter(row => row.familyId).length) {
                            this.childrenListSort();
                        }
                        console.log(this.operationPms)
                        console.log(this.list)
                    }
                    this.getBillTitleBelow(this.operationPms.idTitleDTO).then(() => {
                        this.getBillColumnSetting();
                    })
                }, (e) => {
                    alert('请求异常！');
                }, this.authorization);
            },
            totalListLoad(headers, list) {
                let totalHeaders = ['amount', 'deposit', 'discountAmount', 'num', 'otherCharges', 'qty', 'subAmount', 'taxAmount', 'weight', 'ratio', '', ''];
                let totalMap = [
                    {aName: 'index', width: 0}
                ];
                let totalList = [{}];
                return new Promise((resolve, reject) => {

                    let width = 0;
                    for (let item of headers) {
                        if (width === -1 || totalHeaders.indexOf(item.aName) > -1) {
                            if (width !== -1) {
                                // totalMap[0].width = width - 4;
                                totalMap[0].width = width - 3;
                                width = -1;
                            }
                            totalMap.push({
                                aName: item.aName,
                                width: item.width
                            })
                        } else if (item.width && width !== -1) width += (item.width + 4);

                    }


                    for (let item of list) {
                        for (let h of totalMap) {
                            if (totalHeaders.indexOf(h.aName) > -1) {
                                if (item[h.aName]) {
                                    totalList[0][h.aName] = (totalList[0][h.aName] || 0) + item[h.aName];
                                } else {
                                    totalList[0][h.aName] = 0;
                                }
                            } else {
                                totalList[0][h.aName] = '';
                            }
                        }
                    }

                    totalList[0].index = '合计：大写金额：' + intToChinese(totalList[0].taxAmount || totalList[0].subAmount) + '元整';
                    this.totalMap = totalMap;
                    this.totalList = totalList;
                    resolve();
                });

            },
            html2canvasFun() {

                let canvasDiv = document.getElementById('canvasDiv');
                let height = document.getElementById('myDiv').clientHeight;
                let _this = this;
                html2canvas(document.querySelector('#myDiv'), {
                    useCORS: true, // 允许图片跨域
                    logging: true,
                    // dpi: window.devicePixelRatio * 2, // dpi  如果模糊的话 就把dpi和scale缩放的值调大 dpi越高生成的图片越大
                    width: (this.userPrint.paperWide * this.multiple),
                    height: height || (this.userPrint.paperHigh * this.multiple),
                    background: '#fff',
                    // canvas:myCanvas
                }).then((canvas) => {
                    $('#myDiv').remove();    //移除页面上的该元素
                    canvas.id = "myCanvas";
                    // document.body.prepend(canvas);    //像页面中添加转为canvas之后的元素
                    canvasDiv.append(canvas);

                    let url = canvas.toDataURL();     //把canvas转成base64
                    uni.postMessage({
                        data: {
                            imgData: url, // 刚才拿到的base64 数据
                            width: (_this.userPrint.paperWide * this.multiple),
                            height: height || (_this.userPrint.paperHigh * this.multiple)
                        },
                    });
                    setTimeout(() => {
                        uni.navigateBack()
                    }, 1000)
                });
            },
            getQueryString(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
                var r = window.location.search.substr(1).match(reg);
                if (r != null) return decodeURI(r[2]);
                return null;
            },
            getColumnType(item, type) {
                let lable = item.description;
                let type1Lables = ['单据编码', '单据日期', '客户名称', '结算客户', '手机号码', '所属区域', '销售经理', '销售内勤', '结算方式', '可用余额', '应收余额', '合同单号',
                    '操作时间', '手机号码', '销售日期', '单据编号', '业务类型', '客户简称', '应收款', '信用额度', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx'
                ];
                let type2Lables = ['销售备注', '备注', '审核人', '审核时间', '制单人', '物流', '收货人', '打印次数', '审核日期', 'xxxxx', 'xxxxx', 'xxxxx']
                if (type === 1) {
                    if (type1Lables.indexOf(lable) > -1) {
                        return true;
                    }
                } else if (type === 2) {

                    if (lable === '物流地址' || lable.indexOf('备注') > -1) {
                        item.width100 = true;
                    }

                    if (lable === '物流地址') {
                        item.description = '物流';
                        item.aName = 'logisticsInfo';
                        return true;
                    }

                    if (type2Lables.indexOf(lable) > -1) {
                        return true;
                    }
                }
                return false;
            },
            /*关联产品排序*/
            childrenListSort() {
                let childrens = [];
                let list = [];
                for (let item of this.list) {
                    if (item.parentId) {
                        childrens.push(item);
                    }
                }
                for (let item of this.list) {
                    if (!item.parentId) {
                        list.push(item);
                        if (item.familyId) {
                            for (let item2 of childrens) {
                                if (item.familyId === item2.parentId) {
                                    list.push(item2);
                                }
                            }
                        }
                    }
                }
                this.list = [...list];
            }

        },
    })

</script>


<script type="text/javascript">


    // if (window.plus) {
    //     plusReady();
    // }//加上此判断以免再浏览器打开h5页面时报plus is not define
    // function plusReady() {
    //     if (plus.webview.getWebviewById("batch_view")) {
    //         const appData = plus.webview.getWebviewById("batch_view").data;
    //         alert(JSON.stringfy(appData))
    //     }
    // }


    function downloadImage() {
        const canvas = document.getElementById('myCanvas');
        const dataUrl = canvas.toDataURL('image/png');
        const link = document.createElement('a');
        link.href = dataUrl;
        link.download = 'canvas_image.png';
        link.click();
    }

    function intToChinese(money) {
        let cnNums = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"]; //汉字的数字
        let cnIntRadice = ["", "拾", "佰", "仟"]; //基本单位
        let cnIntUnits = ["", "万", "亿", "兆"]; //对应整数部分扩展单位
        let cnDecUnits = ["角", "分", "毫", "厘"]; //对应小数部分单位
        //var cnInteger = "整"; //整数金额时后面跟的字符
        let cnIntLast = ''; //整型完以后的单位
        let isNegative = false; // 金额是否为负数

        let maxNum = 999999999999999.9999; //最大处理的数字
        let IntegerNum; //金额整数部分
        let DecimalNum; //金额小数部分
        let ChineseStr = ""; //输出的中文金额字符串
        let parts; //分离金额后用的数组，预定义
        if (money === "") return "";
        // 如果值小于0, 则取整后再继续
        if (money < 0) {
            isNegative = true;
            money = Math.abs(money);
        }
        if (money && money.toString() && money.toString().indexOf('.') > -1) cnIntLast = "元"; //整型完以后的单位
        money = parseFloat(money);

        if (money === 0) return cnNums[0] + cnIntLast;
        money = money.toString(); //转换为字符串
        if (money.indexOf(".") === -1) {
            IntegerNum = money;
            DecimalNum = '';
        } else {
            parts = money.split(".");
            IntegerNum = parts[0];
            DecimalNum = parts[1].substr(0, 4);
        }
        if (parseInt(IntegerNum, 10) > 0) {//获取整型部分转换
            let zeroCount = 0;
            let IntLen = IntegerNum.length;
            for (let i = 0; i < IntLen; i++) {
                let n = IntegerNum.substr(i, 1);
                let p = IntLen - i - 1;
                let q = p / 4;
                let m = p % 4;
                if (n === "0") {
                    zeroCount++;
                } else {
                    if (zeroCount > 0) ChineseStr += cnNums[0];
                    zeroCount = 0; //归零
                    ChineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
                }
                if (m === 0 && zeroCount < 4) ChineseStr += cnIntUnits[q];
            }
            ChineseStr += cnIntLast;
            //整型部分处理完毕
        }
        if (DecimalNum !== '') {//小数部分
            let decLen = DecimalNum.length;
            for (let i = 0; i < decLen; i++) {
                let n = DecimalNum.substr(i, 1);
                if (n !== '0') ChineseStr += cnNums[Number(n)] + cnDecUnits[i];
            }
        }
        if (ChineseStr === '') {
            //ChineseStr += cnNums[0]+cnIntLast+cnInteger;
            ChineseStr += cnNums[0] + cnIntLast;
        }/* else if( DecimalNum == '' ){
                ChineseStr += cnInteger;
                ChineseStr += cnInteger;
            } */
        return ChineseStr;
    }
</script>


</body>
</html>





